﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chapter21.Models.ThreadSamples
{
    using System.Threading;

    public static class Demo
    {
        public static void InvokeAll()
        {
            Action line = () =>
            {
                Console.ReadLine();
            };
            Invoke(Start, line, StartWithLambda, line, StartWithParameters, line, StartWithParametersClass, line, BackgroundThread, line);
        }

        public static void Invoke(params Action[] actions)
        {
            foreach (var action in actions)
            {
                action();
            }
        }

        public static void Start()
        {
            var t = new Thread(ThreadMain);
            t.Start();
            Console.WriteLine("这里是主调线程");
        }

        public static void ThreadMain()
        {
            Console.WriteLine("运行一个线程");
        }

        public static void StartWithLambda()
        {
            var t = new Thread(() =>
            {
                Console.WriteLine("在一个线程中运行, Id: {0}", Thread.CurrentThread.ManagedThreadId);
            });
            t.Start();
            Console.WriteLine("这是一个主调线程, Id: {0}", Thread.CurrentThread.ManagedThreadId);
        }

        public static void StartWithParameters()
        {
            var d = new Data { Message = "信息" };
            var t = new Thread(ThreadMainWithParameters);
            t.Start(d);
            Console.WriteLine("这是一个主调线程, Id: {0}", Thread.CurrentThread.ManagedThreadId);
        }

        public static void ThreadMainWithParameters(object obj)
        {
            var d = (Data)obj;
            Console.WriteLine("在一个线程中运行, 已收到参数: {0}", d.Message);
        }

        public static void StartWithParametersClass()
        {
            var obj = new MyThread("信息");
            var t = new Thread(obj.ThreadMain);
            t.Start();
        }

        public static void BackgroundThread()
        {
            var t = new Thread(() =>
            {
                Console.WriteLine("线程 {0} 已经开始", Thread.CurrentThread.Name);
                Thread.Sleep(3000);
                Console.WriteLine("线程 {0} 已经完成", Thread.CurrentThread.Name);
            }) { Name = "我的新线程", IsBackground = false };
            t.Start();
            Console.WriteLine("主调线程正在结束");
        }
    }
}
